package com.hermeneute.fsa.parser;

import java.io.StringReader;
import java.util.Iterator;

import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.collections.AST;

public class FSTParserTreeTK {
	FSTParserTree parser = null;

	FSTLexerTree lexer = null;

	public FSTParserTreeTK(String content) {
		StringReader rdr = new StringReader(content);
		ExtentLexerSharedInputState lsis = new ExtentLexerSharedInputState(rdr);

		lexer = new FSTLexerTree(lsis);

		lexer.setTokenObjectClass(ValueExtentToken.class.getName());
		parser = new FSTParserTree(lexer);
		parser.init();
		try {
			parser.file();
		} catch (RecognitionException e) {
			e.printStackTrace();
		} catch (TokenStreamException e) {
			e.printStackTrace();
		}
	}

	public FSTParserTreeTK() {
		ExtentLexerSharedInputState lsis = new ExtentLexerSharedInputState(
				System.in);

		lexer = new FSTLexerTree(lsis);
		lexer.setTokenObjectClass(ValueExtentToken.class.getName());
		parser = new FSTParserTree(lexer);
		//parser.setASTNodeClass(TokenAST.class.getName());
		parser.init();
		try {
			parser.file();
		} catch (RecognitionException e) {
			e.printStackTrace();
		} catch (TokenStreamException e) {
			e.printStackTrace();
		}
	}

	public FSTParserTree getParser() {
		return parser;
	}

	public Object[] getRootChildren() {
		AST t = parser.getAST();
		Object ch[] = null;
		int s = 0;
		while (t != null) {
			t = t.getNextSibling();
			s++;
		}
		t = parser.getAST();
		ch = new Object[s];
		s = 0;
		while (t != null) {
			ch[s++] = t;
			t = t.getNextSibling();
		}
		return ch;
	}

	public String[] getAutomata() {
		String [] res = new String[parser.getAutomata().size()];
		Iterator it = parser.getAutomata().iterator();
		for (int i=0;it.hasNext();i++) {
			res[i] = (String)it.next();
		}
		return res;
	}
}
